from flask import Blueprint, request,jsonify,redirect
from db import db
from utils.comm import gain_data,qntoken, send_message
import time,json,math,random

acti = Blueprint('act',__name__)

@acti.route('/add',methods = ['POST','GET'])
def add():
    if request.method == 'POST':
        gain = gain_data()
        print(gain)
        t_time = time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time()))
        sql = """
            insert into activity(id,title,titlename,address,stime,total_time,t_count,use_count,price) value(0,'%s','%s','%s','%s',%f,%d,%d,%f)
        """%(gain['title'],gain['titlename'],gain['address'],t_time,int(gain['total_time']),int(gain['t_count']),int(gain['t_count']),int(gain['price']))
        db.insert(sql)
        return jsonify({"code":200})
    else:
        sql = """
            select *from activity
        """
        res = db.findall(sql)
        return ({"code":200,'matter':res})

@acti.route('/activityRecord',methods=['POST','GET'])
def record():
    if request.method == 'POST':
        gain = gain_data()
        # 查询用户
        sql = """
            select *from users where mobile='%s'
        """%(int(gain['mobile']))
        res = db.find(sql)

        # 查询活动剩余人数
        sql1 = """
            select *from activity where id=%d
        """%(int(gain['a_id']))
        res1 = db.find(sql1)

        # 生成流水号
        dtime = time.strftime('%Y%m%d%H%M%S', time.localtime())
        num = random.randint(100000,999999)
        serial_number = str(num)+str(dtime)
        if res:
            if res['level'] == 1:
                # 查询用户是否已参加活动
                sql2 = """
                    select *from activation_record where mobile='%s' and a_id=%d
                """%(gain['mobile'],int(gain['a_id']))
                res2 = db.find(sql2)
                if res2:
                    return jsonify({'code':10030,'matter':'你已参加活动'})
                else:
                    # 添加活动记录
                    sql = """
                        insert into activation_record(id,mobile,a_id,type,state,price,serial_number) value(0,'%s',%d,1,1,%d,'%s')
                    """%(gain['mobile'],int(gain['a_id']),int(res1['price']),serial_number)
                    db.insert(sql)
                    # 更新剩余人数
                    count = int(res1['use_count'])-1
                    sql1 = """
                        update activity set use_count=%d where id=%d
                    """%(count,int(gain['a_id']))
                    db.update(sql1)
                    return jsonify({'code':200,'matter':'参与成功'})
            else:
                # 该用户不是超级vip
                return jsonify({'code':10010,'matter':'没有权限参加'})
        else:
            # 添加活动记录
            sql = """
                insert into activation_record(id,mobile,a_id,type,state,price,serial_number) value(0,'%s',%d,2,2,%d,'%s')
            """%(gain['mobile'],int(gain['a_id']),int(res1['price']),serial_number)
            db.insert(sql)
            # 查询该订单
            sql3 = """
                select id,price from activation_record where mobile='%s' and a_id=%d
            """%(gain['mobile'],int(gain['a_id']))
            res3 = db.find(sql3)
            return jsonify({'code':10020,'matter':res3})
    else:
        pass


from utils.comm import get_ali_object
@acti.route('/pay')
def get():
        id = request.args.get('id')
        sql = """
            select *from activation_record where id=%d
        """%(int(id))
        res = db.find(sql)
        print(res)

        alipay = get_ali_object()

        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="小蜜蜂",  # 商品简单描述
            out_trade_no=res['serial_number'],  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(res['price']),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return jsonify({'code':200,'matter':pay_url})

